class SocketTask {
	constructor() {
		this.socketUrl = getApp().globalData.socketUrl;
		this.socketStart = false;
		this.socketReceive();
	}
	setMethod(handler1,handler2,handler3) {
		this.cartCount = handler1;
		this.clearCart = handler2;
		this.orderList = handler3;
	}
	init() {
		if (this.socketStart) {
			console.log("已启动WebSocket连接");
		} else {
			let url = this.socketUrl;
			uni.connectSocket({
				url: url,
				method: 'GET',
			});
			uni.onSocketOpen((res) => {
				this.socketStart = true;
				console.log("已启动WebSocket");
			})

		}
	}
	socketReceive() {
		uni.onSocketMessage((res) => {
			if(res.data == "delCart" ){
				this.clearCart();
			}else if(res.data == "add"){
				this.orderList();
			}else{
				let data = JSON.parse(res.data);
				if (this.cartCount) {
					this.cartCount(data);
				}
			}
			
		});
	}
	closeSocket() {
		uni.closeSocket();
		console.log("已关闭WebSocket");
	}

};
const webSocket = new SocketTask();
export default webSocket;